using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SpaceShooter.ParticleSystem;
using SpaceShooter.Common;

namespace SpaceShooter.GameObjects
{
    public abstract class Missile : GameObject
    {
        private TimeSpan remainingFlightTime = TimeSpan.MinValue;
        private ParticleEmitter trailEmitter;

        public Missile(IGameScreen gameScreen, string modelName)
            : base(gameScreen, modelName)
        {
            this.Initialize();
        }

        public Missile(IGameScreen gameScreen, string modelName, TimeSpan flightTime)
            : base(gameScreen, modelName)
        {
            this.remainingFlightTime = flightTime;
            this.Initialize();
        }

        public override void Initialize()
        {
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            if (this.remainingFlightTime != TimeSpan.MinValue)
            {
                this.remainingFlightTime -= gameTime.ElapsedGameTime;

                if (this.remainingFlightTime < TimeSpan.Zero)
                {
                    this.MissileSelfDestroy();
                }
            }

            if (this.trailEmitter == null)
            {
                this.trailEmitter = new ParticleEmitter(ParticleSystemManager.TrailParticleSystem, 200f, this.Position);
            }

            this.trailEmitter.Update(gameTime, this.Position);
        }

        private void MissileSelfDestroy()
        {
            this.AddSmoke(40);
            this.RemoveFlag = true;
        }

        protected override void Explode()
        {
            base.Explode();
            ExplosionParticleSystemHelper.Explode(50, 30, this);
        }

        private void AddSmoke(int numberOfParticles)
        {
            Times(numberOfParticles, () => ParticleSystemManager.ExplosionSmokeParticleSystem.AddParticle(this.Position, Vector3.Zero));
        }

        private void Times(int numberOfParticles, Action action)
        {
            for (int i = 0; i < numberOfParticles; i++)
            {
                action();
            }
        }
    }
}
